package com.sdhs.paas.codegenerate.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sdhs.paas.codegenerate.bean.Attribute;
import com.sdhs.paas.codegenerate.bean.CodeGenerateBean;
import com.sdhs.paas.codegenerate.bean.Column;
import com.sdhs.paas.codegenerate.bean.EntityParameter;
import com.sdhs.paas.codegenerate.service.GenerateCodeService;

/**
 * @author kjc
 * @version 1.0
 * @Title:  代码生成器
 * @date 2018/7/22/21:26
 */
public class CodeGenerationUtils {

    /**
     * java代码生成接口
     * @param 模板名称
     * @return 返回生成成功的实体路径
     */
    public String createdJavaCode(String templateName) {
    	String result = "success";
    	/**
    	 * 1.读取templateConfig.yml里面配置的信息
    	 * packageName:包名
    	 * className:类名 
    	 * columns:[
    	 * 		{
    	 * 			columnName:列名，
    	 * 			columnType:类型，
    	 * 			cloumnZhName:中文名称，
    	 * 			columRemark:备注
    	 * 		}
    	 * ]
    	 * 2.将读取到的配置信息赋值给EntityParameter对象
    	 * 3.根据EntityParameter对象和ftl模板生成具体的java代码，生成内容如下：
    	 * bean:数据库中table对应的实体类
    	 * dto: 请求响应所需的java类
    	 * repository:Mapper接口
    	 * service:所需的接口
    	 * controller:业务逻辑层
    	 * MapperXML:mybatis xml文件
    	 * 
    	 * */
    	//读取yml的内容，并将值赋值给CodeGenerateBean对象
    	FreeMarkerConfigUtils config = new FreeMarkerConfigUtils();
    	CodeGenerateBean codeGenerateBean = config.getYamlBean(templateName);
        try {
        	//生成具体的java代码
            String entityURL = generateJavaCode(codeGenerateBean);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 后台代码生成
     * @param entityParameter 前台接收到的实体
     * @return  成功 -----> 对应类的类路径，失败 ------> null
     */
    public String generateJavaCode(CodeGenerateBean codeGenerateBean){
    	//包名
    	String packageName = codeGenerateBean.getPackageName();
    	//类名
    	String className = Utils.fristWordToUpperCase(codeGenerateBean.getClassName());
    	//表名
    	String tableName = codeGenerateBean.getTableName();
    	//作者
    	String author = codeGenerateBean.getAuthor();
    	//属性列
    	List<Column> columns = codeGenerateBean.getColumns();
    	//获取项目根路径
//    	String rootPath = this.getClass().getResource("/").getPath();
    	// E:\git\sdhs-paas-codegenerate        \src\main\java\
    	String projectRootPath = System.getProperty("user.dir");
    	//将包名转为具体的路径
    	String packageDirName = packageName.replace(".", "\\");
    	//项目+\src\main\java\+包路径 = 组装成具体的路径
    	String realPath = projectRootPath+"\\src\\main\\java\\"+packageDirName+"\\";
    	String xmlPath = projectRootPath+"\\src\\main\\resources\\com\\sdhs\\app\\repository\\";
    	List<Attribute> attr_list = new ArrayList<Attribute>();
        for (Column column : codeGenerateBean.getColumns()){
            attr_list.add(new Attribute(column.getColumName(), column.getColumType()));
        }
        String columnsToString = getColumnsToString(attr_list);
    	// 数据预处理
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("className", className);
        root.put("tableName", tableName);
        root.put("realPath", realPath);
        root.put("xmlPath", xmlPath);
        root.put("author", author);
        root.put("attrs", attr_list);
        root.put("columns",columnsToString);
        root.put("nativecolumns",columns);
        root.put("packageName", packageName);
        root.put("date", Utils.typeThree(new Date()));
        //生成实体类
        String result = GenerateCodeService.generateEntity(root);
        //生成dto
        GenerateCodeService.generateDTO(root);
        //生成resDTO
        GenerateCodeService.generateResDTO(root);
        //生成reqDTO
        GenerateCodeService.generateReqDTO(root);
        //生成mapper接口代码
        GenerateCodeService.generateMapperInterface(root);
        //生成mapperXML文件
        GenerateCodeService.generateMapperXML(root);
        //生成service代码
        GenerateCodeService.generateService(root);
        //生成controller的代码
        GenerateCodeService.generateController(root);
        //生成实体类java代码
    	return "success";
    }
    public String generateJavaCode(EntityParameter entityParameter) {
        // 获取配置文件信息
        HashMap config = FreeMarkerConfigUtils.getConfig("templateConfig.yml");

        HashMap javaConfig = (HashMap) ((HashMap) config.get("generator")).get("java");

        HashMap javaCode = (HashMap) javaConfig.get("code");

        HashMap javaCodePackage = (HashMap) javaConfig.get("package");

        // 数据预处理
        Map<String, Object> root = new HashMap<String, Object>();
        String className = entityParameter.fristWordToUpperCase(entityParameter.getEntityName());
        root.put("entityPackageName", javaCodePackage.get("entityPackage").toString());
        root.put("servicePackageName", javaCodePackage.get("servicePackage").toString());
        root.put("serviceImplPackageName",javaCodePackage.get("serviceImplPackage").toString());
        root.put("controllerPackageName",javaCodePackage.get("controllerPackage").toString());
        root.put("mapperPackageName",javaCodePackage.get("mapperPackage").toString());
        root.put("className", className);
        root.put("author", "官江涛");
        root.put("date", Utils.typeThree(new Date()));
        List<Attribute> attr_list = new ArrayList<Attribute>();
        for (Column column : entityParameter.getColumns()){
            attr_list.add(new Attribute(column.getColumName(), column.getColumType()));
        }
        String entityURL = "success";
//        String columnsToString = getColumnsToString(attr_list);
//        root.put("attrs", attr_list);
//        root.put("columns",columnsToString);
//        // 生成Entity
//        String entityURL = generatorBackEndService.generateEntity(root,javaCode.get("entityPath").toString());
//        // 生成service代码
//        generatorBackEndService.generateService(root,javaCode.get("servicePath").toString());
//        // 生成Controller代码
//        generatorBackEndService.generateController(root,javaCode.get("controllerPath").toString());
//        //  生成serviceImpl代码
//        generatorBackEndService.generateServiceImpl(root,javaCode.get("serviceImplPath").toString());
//        //  生成javaMapper代码
//        generatorBackEndService.generateJavaMapper(root,javaCode.get("mapperPath").toString());
//        // 生成XMLMapper代码
//        generatorBackEndService.generateXMLMapper(root,javaCode.get("xmlPath").toString());
        return entityURL;
    }
    
    /**
     *  将所有的字段拼接成一个字符串，用于创建构造方法
     * @param attrs 需要拼接的参数
     * @return    拼接好的字段
     */
    private String getColumnsToString(List<Attribute> attrs) {
        StringBuffer stringBuffer = new StringBuffer();
        attrs.forEach(
                (attr) -> stringBuffer.append(attr.getType()+" "+attr.getName()+ ","));
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        return stringBuffer.toString();
    }
    
    public static void main(String[] args) {
//    	FreeMarkerConfigUtils config = new FreeMarkerConfigUtils();
//    	CodeGenerateBean codeGenerateBean = config.getYamlBean("templateConfig.yml");
//    	System.out.println(codeGenerateBean.getAuthor());
//    	System.out.println(codeGenerateBean.getClassName());
//    	System.out.println(codeGenerateBean.getPackageName());
//    	System.out.println(codeGenerateBean.getColumns().size());
    	CodeGenerationUtils codeGenerationUtils = new CodeGenerationUtils();
    	codeGenerationUtils.createdJavaCode("templateConfig.yml");
    	String packageName = "com.sdhs.paas.codegenerate";
    	//com\sdhs\paas\codegenerate
//    	System.out.println(packageName.replace(".", "\\"));

	}
}
